﻿using System;
using System.Net.Mail;
using System.Data.SqlClient;
using Outils;

namespace App_Recherche
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string IdContact = Request.QueryString["id"];
            int Id = 0;
            //Si premier chargement 
            if (!IsPostBack)
            {
                if (int.TryParse(IdContact, out Id))
                {
                    //string CnxInterimaire = "Data Source=PILOTT-LGZ;Initial Catalog=Interimaires;Integrated Security=True;Pooling=False";
                    SqlConnection SqlC = new SqlConnection(Utils.CnxInterimaire);

                    SqlC.Open();
                    SqlCommand SQLCmd = SqlC.CreateCommand();
                    SQLCmd.CommandText = "SELECT Email FROM  Interimaire WHERE Id = '" + Id + "'";
                    SqlDataReader SqlReader = SQLCmd.ExecuteReader();

                    while (SqlReader.Read() && SqlReader != null)
                    {
                        //Adresse mail de l'interimaire qui peut être changer manuellement par l'utilisateur
                        tbDestinataire.Text = (string)SqlReader["Email"];
                    }
                    SqlC.Close();
                }
            }
            //si second chargment 
            else
            {
                /* Cette condition est utile pour la modiffication de 
                 * l'adresse mail de l'intérimaire pas l'utilisateur de la recherche
                 */
            }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(tbDestinataire.Text) && !string.IsNullOrEmpty(tbObjet.Text))//sans ce test l'application plantera 
            {
                MailMessage email = new MailMessage();
                email.From = new MailAddress("gdegnero@gmail.com");
                email.To.Add(tbDestinataire.Text);
                email.Subject = tbObjet.Text;
                email.Body = tbMessage.Text;

                SmtpClient smtp = new SmtpClient();
                smtp.Host = "smtp.gmail.com";
                smtp.Port = 587;
                smtp.UseDefaultCredentials = false;
                smtp.Credentials = new System.Net.NetworkCredential("gdegnero@gmail.com", "azerty38");
                smtp.EnableSsl = true;

                smtp.Send(email);
                Response.Redirect("~/Page_aspx/Default.aspx?id=" + (int)Utils.TypePage.contact);
            }
            else
            {
                MessageDest.Text = "Erreur dans la saisie recommencez";

            }
        }



        protected void reset_Click(object sender, EventArgs e)
        {
        }
    }
}
